import React, { useEffect, useState, useRef, useMemo } from 'react'
import { useParams, useLocation } from 'react-router-dom'
import { Skeleton, List } from 'react-vant'
import {
  ArrowLeft,
  Ellipsis,
  Exchange,
  ChatO,
  GoodJobO,
  CommentO
} from '@react-vant/icons'
import { getDate } from '@/util/index'
import Card from '@/components/Card'
import ShareComponent from '@/hooks/share'
import { extend, banner, hotflow } from '@/api/index'
import './index.less'
import '../../components/Card/index.less'

const actions = [{ name: '复制链接' }, { name: '分享' }]

const Index = () => {
  const Params = useParams()
  const { state } = useLocation()
  const { id } = Params
  const [text, setText] = useState('')
  const [img, setImg] = useState('')
  const [skeleton, setSkeleton] = useState(true)
  const [index, setIndex] = useState(1)
  const [commentList, setCommentList] = useState([])
  const [finished, setFinished] = useState(true)
  const [max_id, setID] = useState('')
  let [max, setMax] = useState('')
  let [num, setNum] = useState(1)
  let [commentMsg, setCommentMsg] = useState('')

  const shareComponentRef = useRef(null)
  const shareComponent = useMemo(
    () => (
      <ShareComponent
        ref={shareComponentRef}
        actions={actions}
        shareContent={state.item}
      />
    ),
    [state.item]
  )

  const back = () => {
    window.history.back(-1)
  }

  // 骨架屏
  const wbSkeleton = () => {
    let s = [...Array.from({ length: 4 }).keys()]
    return (
      <>
        {s.map((item, idx) => {
          return (
            <div key={idx} className="weibo-skeleton">
              <Skeleton
                avatar
                title
                row={5}
                round={false}
                rowHeight={10}
                rowWidth={['100%', '100%', '100%']}
              />
              <footer className="f-footer-ctrl">
                <div className="m-diy-btn m-box-center-a">
                  <Exchange className="lite-iconf lite-iconf-report" />
                  <h4>转发</h4>
                </div>
                <div className="m-diy-btn m-box-center-a">
                  <ChatO className="lite-iconf lite-iconf-comments" />
                  <h4>评论</h4>
                </div>
                <div className="m-diy-btn m-box-center-a">
                  <GoodJobO className="lite-iconf lite-iconf-like" />
                  <h4>赞</h4>
                </div>
                <aside onClick={() => cardShow(idx)}>
                  <Ellipsis />
                </aside>
              </footer>
            </div>
          )
        })}
      </>
    )
  }

  const initDetail = () => {
    let data = extend({
      id
    }).then(res => {
      setText(res.data.longTextContent)
      return res
    })
    return data
  }

  const initBanner = () => {
    let data = banner({
      position: 5
    }).then(res => {
      setImg(res.data.image)
      return res
    })
    return data
  }

  const ShowHtml = ({ htmlStr }) => (
    <h3 dangerouslySetInnerHTML={{ __html: htmlStr }}></h3>
  )

  const initHotflow = async type => {
    setNum(++num)
    if (type == 'f') {
      let data = await hotflow({
        id,
        mid: id,
        max_id_type: 0
      })
      if (data.ok == 0) {
        setCommentMsg(data.msg)
      } else {
        setID(pre => {
          pre = data.data.max_id
          return pre
        })
        setCommentList(list => {
          return [...list, ...data.data.data]
        })
      }
      return data
    }
    if (type === 'm') {
      let data = await hotflow({
        id,
        mid: id,
        max_id: max_id,
        max_id_type: 0
      })
      console.log(data)
      setID(pre => {
        pre = data.data.max_id
        return pre
      })
      if (data.ok == 1) {
        setCommentList(list => {
          return [...list, ...data.data.data]
        })
      }
      if (num >= max) {
        setFinished(true)
        return false
      }
      return data
    }
  }

  const transmit = () => {
    setIndex(0)
  }

  const comment = () => {
    setIndex(1)
  }

  const support = () => {
    setIndex(2)
  }

  const clickShow = () => {
    shareComponentRef.current.showMenu()
  }

  useEffect(() => {
    window.scrollTo(0, 0)
    Promise.all([initDetail(), initBanner(), initHotflow('f')]).then(res => {
      if (res[2].ok == 0) {
        return false
      } else {
        setMax(res[2].data.max)
      }
    })
    setSkeleton(false)
  }, [])

  return (
    <>
      {skeleton ? wbSkeleton() : false}
      <div className="lite-page-wrap">
        <div className="lite-topbar lite-page-top">
          <div onClick={back} className="nav-left">
            <ArrowLeft />
          </div>
          <div className="nav-main">
            <h4>微博正文</h4>
          </div>
          <div className="nav-right" onClick={clickShow}>
            <Ellipsis />
          </div>
        </div>
        <div className="main" style={{ marginTop: '2.75rem' }}>
          <Card type={'detali'} state={state} text={text} url={img} />
        </div>
        <div className="lite-page-tab">
          <div
            onClick={transmit}
            className={['tab-item', index == 0 ? 'cur' : null].join(' ')}
          >
            <i>
              转发
              <em></em>
            </i>
            <i>{state.item.mblog.reposts_count}</i>
          </div>
          <div
            onClick={comment}
            className={['tab-item', index == 1 ? 'cur' : null].join(' ')}
          >
            <i>
              评论
              <em></em>
            </i>
            <i>{state.item.mblog.comments_count}</i>
          </div>
          <div
            onClick={support}
            className={['tab-item', index == 2 ? 'cur' : null].join(' ')}
          >
            <i>
              赞<em></em>
            </i>
            <i>{state.item.mblog.attitudes_count}</i>
          </div>
        </div>
        <List finished={finished} onLoad={() => initHotflow('m')}>
          <div className="comment-content">
            {commentList.length <= 0 ? (
              <div className="empty">{commentMsg}</div>
            ) : (
              commentList.map((item, idx) => {
                return (
                  <div key={idx} className="card m-avatar-box lite-page-list">
                    <div className="card-wrap">
                      <div className="card-main">
                        <div className="m-box">
                          <div className="m-img-box">
                            <img src={item.user.avatar_hd} alt="" />
                            <i className="m-icon m-icon-club"></i>
                          </div>
                          <div className="m-box-col m-box-dir m-box-center lite-line">
                            <div className="m-box">
                              <div className="m-box-col m-box-dir">
                                <div className="m-text-box">
                                  <h4 className="m-text-cut">
                                    {item.user.screen_name}
                                  </h4>
                                  <ShowHtml htmlStr={item.text} />
                                </div>
                                <div className="lite-bot m-text-cut">
                                  <div className="m-box-center-a time">
                                    {' '}
                                    {getDate(item.created_at)} {item.source}{' '}
                                  </div>
                                  <aside>
                                    <CommentO />
                                  </aside>
                                  <aside>
                                    <GoodJobO />
                                    <em>{item.like_count}</em>
                                  </aside>
                                </div>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                )
              })
            )}
          </div>
        </List>
      </div>
      {shareComponent}
    </>
  )
}

export default Index
